package com.help10000.rms.mvp.presenter

import android.util.Log
import com.amir.common.api.CustomObserver
import com.amir.common.beans.BaseResult
import com.amir.common.beans.OrderWrapperEntity
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.utils.Constant
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.amir.common.utils.Utils
import com.help10000.rms.mvp.view.OrderView
import com.help10000.rms.ui.activitys.OrderActivity
import com.help10000.rms.utils.LocationManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @Author: amir
 * @Date: 2021/8/1 3:54 下午
 */
open class OrderPresenter(view: OrderView) : BasePresenter<OrderView>(view) {
    // 自定义协程作用域，绑定生命周期（Job用于取消）
    protected val coroutineScope = CoroutineScope(Dispatchers.Main + Job())

    fun robOrder(repairId: String,activity:OrderActivity) {
        coroutineScope.launch(Dispatchers.IO) {
            try {
                val (lat, lng) = LocationManager.getLocation(activity)
                Log.d("抢单定位", "获取到经纬度：lat=$lat, lng=$lng")

                val accessToken = SPUtils.getString(Constant.AccessToken)
                val robOrderAPi = Model.getServer().robOrder(accessToken, repairId, lat, lng)

                withContext(Dispatchers.Main) {
                    Model.getObservable(robOrderAPi, object : CustomObserver<BaseResult>(mvpView) {
                        override fun success(t: BaseResult) {
                            mvpView?.robSuccess(repairId)
                        }

                        override fun onError(e: Throwable) {
                            super.onError(e)
                            ToastUtil.show("抢单失败：${e.message}")
                        }
                    })
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    ToastUtil.show("抢单异常：${e.message}")
                }
            }
        }
    }

    fun playVoice(path: String) {
        coroutineScope.launch(Dispatchers.Main) {
            mvpView?.playVoice(path)
        }
    }

    fun getTimeOutOrderList(pageNo: Int) {
        coroutineScope.launch(Dispatchers.IO) {
            try {
                val accessToken = SPUtils.getString(Constant.AccessToken)
                val kw = ""
                val overTimeOrderList = Model.getServer().overTimeOrderList(accessToken, kw, pageNo)

                withContext(Dispatchers.Main) {
                    Model.getObservable(
                        overTimeOrderList,
                        object : CustomObserver<OrderWrapperEntity>(mvpView) {
                            override fun success(t: OrderWrapperEntity) {
                                mvpView?.onDataSuccess(t.data.OrderList)
                            }

                            override fun onError(e: Throwable) {
                                super.onError(e)
                                ToastUtil.show("获取超时订单失败：${e.message}")
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    ToastUtil.show("获取超时订单异常：${e.message}")
                }
            }
        }
    }

    /**
     * 获取抢单数据
     */
    fun getRobOrderList(activity: OrderActivity) {
        coroutineScope.launch(Dispatchers.IO) {
            try {
                // 在协程内部获取定位信息
                val (lat, lng) = LocationManager.getLocation(activity)
                Log.d("获取抢单数据定位", "获取到经纬度：lat=$lat, lng=$lng")

                // 获取其他参数
                val accessToken = SPUtils.getString(Constant.AccessToken)
                val cmpyCode = SPUtils.getString(Constant.CmpyCode)

                // 在同一个协程内执行网络请求
                val robOrderListAPi = Model.getServer()
                    .robOrderListAPi(accessToken, cmpyCode, lat = lat, lng = lng)

                // 使用withContext切换到主线程处理结果
                withContext(Dispatchers.Main) {
                    Model.getObservable(
                        robOrderListAPi,
                        object : CustomObserver<OrderWrapperEntity>(mvpView) {
                            override fun success(t: OrderWrapperEntity) {
                                mvpView?.onDataSuccess(t.data.OrderList)
                            }

                            override fun onError(e: Throwable) {
                                super.onError(e)
                                ToastUtil.show("获取抢单数据失败：${e.message}")
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                // 处理异常，例如显示错误信息
                withContext(Dispatchers.Main) {
                    ToastUtil.show("获取抢单数据异常：${e.message}")
                }
            }
        }
    }

    /**
     * 获取服务历史
     */
    fun getServiceHistory(pageNo: Int, tel: String?) {
        coroutineScope.launch(Dispatchers.IO) {
            try {
                val accessToken = SPUtils.getString(Constant.AccessToken)
                val serviceHis = Model.getServer().ServiceHis(accessToken, tel, pageNo)

                withContext(Dispatchers.Main) {
                    Model.getObservable(serviceHis, object : CustomObserver<OrderWrapperEntity>(mvpView) {
                        override fun success(t: OrderWrapperEntity) {
                            mvpView?.onDataSuccess(t.data.OrderList)
                        }

                        override fun onError(e: Throwable) {
                            super.onError(e)
                            ToastUtil.show("获取服务历史失败：${e.message}")
                        }
                    })
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    ToastUtil.show("获取服务历史异常：${e.message}")
                }
            }
        }
    }

    fun confirmOrder(repairId: String,activity: OrderActivity) {
        coroutineScope.launch(Dispatchers.IO) {
            try {
                val (lat, lng) = LocationManager.getLocation(activity)
                Log.d("确认订单定位", "获取到经纬度：lat=$lat, lng=$lng")

                val accessToken = SPUtils.getString(Constant.AccessToken)
                val confirmOrder = Model.getServer().confirmOrder(accessToken, repairId, lat, lng)

                withContext(Dispatchers.Main) {
                    Model.getObservable(confirmOrder, object : CustomObserver<BaseResult>(mvpView) {
                        override fun success(t: BaseResult) {
                            mvpView?.receiveSuccess(repairId)
                        }

                        override fun onError(e: Throwable) {
                            super.onError(e)
                            ToastUtil.show("确认订单失败：${e.message}")
                        }
                    })
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    ToastUtil.show("确认订单异常：${e.message}")
                }
            }
        }
    }

    // 在Presenter销毁时调用，取消所有协程
    fun onDestroy() {
        coroutineScope.cancel()
    }
}